<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="基地名称" prop="baseName">
        <el-select v-model="pid" placeholder="请选择基地" filterable disabled="true">
          <el-option
            v-for="item in placeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <br />
      <div v-if="!isHidden">
        <el-form-item label="订单id" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="请输入订单id"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="顾客用户名" prop="customer" label-width="150px">
          <el-input
            v-model="queryParams.customer"
            placeholder="请输入顾客用户名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="顾客电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入顾客电话"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['menuOrders:menuOrders:export']"
          >导出</el-button
        >
      </el-col>

      <el-col :span="1.5">
        &emsp;
        <span v-show="pollingIsStart" style="color: grey; font-size: 15px">
          轮询时间间隔(单位:s&emsp;范围5s~30s)
        </span>
        &emsp;
        <el-input-number
          v-show="pollingIsStart"
          v-model="timeInterval"
          :min="5"
          :max="30"
        />
        &emsp;
        <el-button
          v-show="pollingIsStart"
          type="info"
          plain
          icon="Loading"
          @click="startPolling"
          >开启轮询</el-button
        >
      </el-col>
      <el-col :span="1.5">
        &emsp;
        <span v-show="!pollingIsStart" style="color: red; font-size: 15px">
          轮询已开启
        </span>
        &emsp;
        <el-button
          v-show="!pollingIsStart"
          type="info"
          plain
          icon="Loading"
          @click="stopPolling"
          >关闭轮询</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuOrdersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="订单id" align="center" prop="id" width="180px" />
      <el-table-column
        label="订购内容"
        align="center"
        prop="content"
        width="450px"
      />
      <el-table-column label="备注" align="center" prop="notes" width="250px" />
      <el-table-column
        label="顾客用户名"
        align="center"
        prop="customer"
        width="150px"
      />
      <el-table-column
        label="顾客电话"
        align="center"
        prop="phone"
        width="150px"
      />
      <el-table-column
        label="价格(元)"
        align="center"
        prop="price"
        width="150px"
      />
      <el-table-column
        label="成本(元)"
        align="center"
        prop="cost"
        width="150px"
      />
      <el-table-column
        label="基地名称"
        align="center"
        prop="baseName"
        width="180px"
      />
      <el-table-column
        label="支付时间"
        align="center"
        prop="gmtPayment"
        width="200px"
      />
      <el-table-column
        label="购买人在支付宝唯一ID"
        align="center"
        prop="aliPaytradeNo"
        width="250px"
      />
      <el-table-column label="打印" width="150px">
        <template #default="scope">
          <div>
            <el-button type="danger" @click="showPrintDialog(scope.row)"
              >打印</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改点菜订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="menuOrdersRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="printDialogVisible" title="打印详情">
      <div v-if="currentRow" id="printMe">
        订购内容:{{ currentRow.content }}<br />
        备注:{{ currentRow.notes }}<br />
        顾客用户名:{{ currentRow.customer }}<br />
        顾客电话:{{ currentRow.phone }}<br />
        价格:{{ currentRow.price }}<br />
        成本:{{ currentRow.cost }}<br />
        基地名称:{{ currentRow.baseName }}<br />
        支付时间:{{ currentRow.gmtPayment }}<br />
        购买人在支付宝唯一ID:{{ currentRow.aliPaytradeNo }}<br />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="printDialogVisible = false">取消</el-button>
          <el-button type="primary" v-print="printObj">打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MenuOrders">
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
const printDialogVisible = ref(false);
const currentRow = ref(null);
const showPrintDialog = (data) => {
  currentRow.value = data;
  printDialogVisible.value = true;
};

const printShow = ref(true);
const activeRow = ref(null);
const goPrint = (scope) => {
  printShow.value = true;
};
const printObj = ref({
  id: "printMe", // 绑定打印区域id
  popTitle: "打印预览", // 内容标签
  beforeOpenCallback() {
    printShow.value = false;
    console.log("打开之前");
  },
  async openCallback() {
    console.log("执行了打印");
  },
  async closeCallback() {
    console.log("aaa");

    console.log("关闭了打印工具");
  },
});

const handlePrint = async () => {};

const isHidden = ref(false);
import { listPlace } from "@/api/place/place";
import { loadAllParams } from "@/api/page";
// 查询基地列表
const placeList = ref([]);

function getPlaceList() {
  listPlace(loadAllParams).then((response) => {
    placeList.value = response.rows;
  });
}
getPlaceList();

const pollingInterval = ref(null);
const pollingIsStart = ref(true);
const timeInterval = ref(5);
const startPolling = () => {
  if (pid.value == null) {
    ElMessage.error("请先选择基地");
    return;
  }
  isHidden.value = true;
  pollingIsStart.value = false;
  handleQuery();
  pollingInterval.value = setInterval(handleQuery, timeInterval.value * 1000); // 每5秒请求一次
};

const stopPolling = () => {
  isHidden.value = false;
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingIsStart.value = true;
    pollingInterval.value = null;
  }
};
onUnmounted(() => {
  // 组件卸载前确保清除定时器
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
  }
});

import {
  listMenuOrders,
  getMenuOrders,
  delMenuOrders,
  addMenuOrders,
  updateMenuOrders,
} from "@/api/menuOrders/menuOrders";
import { ElMessage, ElNotification } from "element-plus";

const { proxy } = getCurrentInstance();

const menuOrdersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    customer: null,
    phone: null,
    baseName: null,
    gmtPayment: formatDate(new Date())
  },
  rules: {},
});

const allMenuOrderList = ref([]);
const allTotal = ref(0);
const total = ref(0);
const pid = ref(Number(window.localStorage.getItem("id")));
const { queryParams, form, rules } = toRefs(data);
watch([allMenuOrderList, allTotal, pid], ([a, b, c], [a1, b1, c1]) => {
  if (pid.value != null) {
    // console.log(a[0].pid,a1[0].pid,a[0].pid==a1[0].pid,b,b1);
    if (a.length > 0 && a1.length > 0 && a[0].pid == a1[0].pid && b > b1) {
      for (let i = 0; i < b - b1; i++) {
        ElNotification.success({
          title: "有新的订单,单号为"+a[i].id,
          dangerouslyUseHTMLString: true,
          message:
            ` <div style="word-break: break-all; white-space: pre-line;">
       ` +
            "订购内容:" +
            a[i].content +`<br>`+
            "备注:" +
            a[i].notes +
            `
       </div>`,

          duration: 0,
          showClose: true,
          onClick: () => {
            showPrintDialog(a[i]);
          },
        });
      }
    }
  }
});
/** 查询点菜订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.pid = pid.value;
  listMenuOrders(queryParams.value).then((response) => {
    menuOrdersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    content: null,
    notes: null,
    uid: null,
    customer: null,
    phone: null,
    price: null,
    cost: null,
    baseName: null,
    gmtPayment: null,
    aliPaytradeNo: null,
  };
  proxy.resetForm("menuOrdersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  const queryParams = {
    pageNum: 1,
    pageSize: 10000,
    id: null,
    customer: null,
    phone: null,
    baseName: null,
    gmtPayment: formatDate(new Date())
  };
  queryParams.pid = pid.value;
  listMenuOrders(queryParams).then((response) => {
    allMenuOrderList.value = response.rows;
    allTotal.value = response.total;
    loading.value = false;
  });
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加点菜订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getMenuOrders(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改点菜订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuOrdersRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateMenuOrders(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMenuOrders(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除点菜订单编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delMenuOrders(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "menuOrders/menuOrders/export",
    {
      ...queryParams.value,
    },
    `menuOrders_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
 